function repair()
{
	var obj = {};
	obj.url = "index.php?option=com_ketnoi&view=repair&tmpl=raw";
	var callback = function(){
		if($("#grid_repair").length > 0)
		{
			var dataSource = $("#grid_repair").data("kendoGrid").dataSource;
			dataSource.read();
			
		}	
	}
	obj.callback = callback;
	return obj;
}

function repair_addlinhkien(vendor)
{
	if($(".linhkien_select option:selected").length == 0)
	{
		alertify.alert("Vui lòng chọn linh kiện");
	}else
	{
		var option = $(".linhkien_select option:selected");
		var row = JSON.parse($(option).attr("data-json"));
		var check = false;
		$("#table_linhkien tbody tr").each(function(){
			if($(this).find(".idlinhkien_hidden").val() == row.id)
			{
				check = true;
				return;
			}	
		})
		if(!check)
		{
			var tr = $("<tr></tr>");
			var td1 = $("<td></td>");
			var td2 = $("<td></td>");
			var td3 = $("<td></td>");
			var td4 = $("<td></td>");
			var td5 = $("<td></td>");
			var td6 = $("<td class='chosen_nocreate'></td>");
			var td7 = $("<td></td>");
			tr.append(td1);
			tr.append(td2);
			tr.append(td3);
			tr.append(td4);
			tr.append(td5);
			tr.append(td6);
			tr.append(td7);
			td1.append("<input type='hidden' name='linhkien_id[]' class='idlinhkien_hidden' value='"+row.id+"' />" + row.ma);
			td2.append(row.ten);
			var thangbaohanh = $("<input type='text' name='sothangbaohanh_"+row.id+"' value='"+row.sothangbaohanh+"'/>");
			var controlcustomthang = $("<div class='controls custom'></div>");
			controlcustomthang.append(thangbaohanh);
			td3.append(controlcustomthang);
			var counterbaohanh = $("<input type='text' name='sodungluongbaohanh_"+row.id+"' value='"+row.sodungluongbaohanh+"'/>");
			var controlcustomcounter = $("<div class='controls custom'></div>");
			controlcustomcounter.append(counterbaohanh);
			td4.append(controlcustomcounter);
			td5.append("<input type='hidden' name='tuoitho_"+row.id+"' value='"+row.tuoitho+"' />" + number_format(row.tuoitho));
			thangbaohanh.kendoNumericTextBox({
				format: "n0",
				decimals: 0,
				min:0,
				spinners:false
			});
			counterbaohanh.kendoNumericTextBox({
				format: "n0",
				decimals: 0,
				min:0,
				spinners:false
			});
			
			var vendorchosen = $("<select name='linhkien_vendor_"+row.id+"'><option value='0'>Chọn nhà cung cấp</option></select>");
			for(var i = 0;i < vendor.length ;i++)
			{
				var op = "<option value='"+vendor[i].id+"'>"+vendor[i].ma+" - "+vendor[i].ten+"</option>";
				vendorchosen.append(op);
			}
			td6.append(vendorchosen);
			td7.append("<i onclick='removeTrackerLinhkien(this)' style='line-height: 30px;cursor:pointer' class='icon-trash'></i>");
			$("#table_linhkien tbody").append(tr);
			buildGrid("#table_linhkien")
			vendorchosen.chosen();
		}
		
	}
}

function removeRepairLinhkien(el)
{
	jQuery(el).closest("tr").remove();
}

function create_repair()
{
	var obj = {};
	obj.url = "index.php?option=com_ketnoi&view=repair&layout=create&tmpl=raw";
	var callback = function(){
		if($("#tab_create_repair").length > 0)
		{
			initControl("#tab_create_repair");
			initControlrepair();
			initCreaterepair();
		}
	}
	obj.callback = callback;
	return obj;
}

function initControlrepair()
{
	var row_serial;
	var serial_value = 0;
	$("#socounter").input_number({
		format: "n0",
		decimals: 0,
		min:0,
		spinners:false
	});

	$("#socounter").keyup(function(){
		$(this).val();
		if(parseInt(serial_value) > 0)
		{
			$("#tinhtrang_linhkien tbody tr").each(function(){
				var counter_last_use = $(this).data("counterlastuse");
				var closing = $(this).data("closing");
				var tuoitho = $(this).data("tuoitho");
				var socounter = $("#socounter").val();
				var percent = calculateClosing(closing,counter_last_use,socounter,tuoitho);
				percent = 100 - percent;
				var percent_class = getPercentClass(percent);
				$(this).find(".progress").removeClass("progress-warning").removeClass("progress-danger");
				$(this).find(".progress").addClass(percent_class);
				$(this).find(".bar").css("width",percent+"%");
				var counter_diff = parseInt(socounter) - parseInt(counter_last_use);
				var closing_diff = parseInt(closing) - parseInt(counter_diff);
				if(closing_diff < 0 ) closing_diff = 0;
				$(this).find(".barnumber").html(number_format(percent)+"% - " + number_format(closing_diff));
			})
		}
	})
	
	$("#employee").chosentable({
		search_contains: true,
		no_results_text: 'Không tìm thấy:',
		template: function (text, templateData) {
	    	return [
	      		"<div class='k-grid-content'><table><tbody><tr><td>" + templateData.ma + "</td>",
	      		"<td>" + templateData.ten + "</td></tr></tbody></table>",      
	    	].join("");
	  	},
	  	headerTemplate:'<div class="k-grid-header"><div class="k-grid-header-wrap"> <table style="width:100%"><thead><tr><th class="k-header" style="width:50%">Mã nhân viên</th><th class="k-header" >Tên nhân viên</th></tr></thead></table></div></div>'
	});
	
	$("#maloi").chosentable({
		search_contains: true,
		no_results_text: 'Không tìm thấy:',
		template: function (text, templateData) {
	    	return [
	      		"<div class='k-grid-content'><table><tbody><tr><td>" + templateData.ma + "</td>",
	      		"<td>" + templateData.ten + "</td></tr></tbody></table>",      
	    	].join("");
	  	},
	  	headerTemplate:'<div class="k-grid-header"><div class="k-grid-header-wrap"> <table style="width:100%"><thead><tr><th class="k-header" style="width:50%">Mã lỗi</th><th class="k-header" >Tên mã lỗi</th></tr></thead></table></div></div>'
	});
	
	$("#serial").chosen({
		search_contains: true,
		no_results_text: 'Không tìm thấy:'
	});
	var lastValue;
	$("#serial").click(function(){
		lastValue = $(this).val();
	}).change(function(){
			
		var value = $("#serial option:selected").val();
		if(typeof(value) != "undefined" && $.trim(value) != "")
		{
			serial_value = value;
			var socounter = $("#socounter").val();
			if($.trim(socounter) == "")
			{
				$(this).val(lastValue);
				$(this).trigger("liszt:updated");
				alertify.alert("Vui lòng nhập số counter");
				return false;
			}
			
			var option = $("#serial option:selected");
			var row = option.data("row");
			row_serial = row;
			var counter_current_use = row.counter_current_use;
			$("#socounter").input_number({
				format: "n0",
				decimals: 0,
				min:counter_current_use,
				spinners:false,
			});
			var mamay = row.ma_machine;
			var tenmay = row.ten_machine;
			if(row.tenkhachhang != "")
			{
				$("#makhachhang").val(row.makhachhang);
				$("#tenkhachhang").val(row.tenkhachhang);
				$("#idkhachhang").val(row.idkhachhang);
			}
			$("#mamay").val(mamay);
			$("#tenmay").val(tenmay);
			$("#socounterdadung").val(number_format(row.counter_current_use));	
			var link = "index.php?option=com_ketnoi&view=repair&task=repair.loadlinhkien&serial="+value;
			showLoader($('#tab_create_repair'));
			
			$.get(link,"",function(response){
				$("#tinhtrang_linhkien tbody").html("");
				var items = JSON.parse(response);
				
				for(var i = 0;i < items.length;i++)
				{
					var tr = $("<tr></tr>");
					var td1 = $("<td></td>");
					var td2 = $("<td></td>");
					var td3 = $("<td></td>");
					var td4 = $("<td></td>");
					var td5 = $("<td></td>");
					var td6 = $("<td class='chosen_nocreate'></td>");
					var td7 = $("<td></td>");
					var td8 = $("<td></td>");
					tr.append(td1);
					tr.append(td2);
					tr.append(td3);
					tr.append(td4);
					tr.append(td5);
					tr.append(td6);
					tr.append(td7);
					tr.append(td8);
					td1.append(items[i].malinhkien + "<input type='hidden' name='repair_linhkien[]' value='"+items[i].id+"' />");	
					td2.append(items[i].tenlinhkien);
					td3.append(items[i].sothangbaohanh);
					td4.append(number_format(items[i].sodungluongbaohanh));
					td5.append(number_format(items[i].tuoitho));
					td6.append(items[i].manhacungcap + " - " +items[i].tennhacungcap);
					
					tr.attr("data-counterlastuse",counter_current_use);
					tr.attr("data-closing",items[i].closing);
					tr.attr("data-tuoitho",items[i].tuoitho);
					var percent = calculateClosing(items[i].closing,counter_current_use,socounter,items[i].tuoitho);
					percent = 100 - percent;
					var percent_class = getPercentClass(percent);	
					var counter_diff = parseInt(socounter) - parseInt(counter_current_use);
					var closing_diff = parseInt(items[i].closing) - parseInt(counter_diff);
					if(closing_diff < 0 ) closing_diff = 0;
					td7.append('<div class="progress custom progress-striped '+percent_class+' active"><div class="bar" style="width: '+percent+'%;"></div><div class="barnumber">'+number_format(percent)+'% - '+number_format(closing_diff)+'</div></div>');
					td8.append("<select name='theodoi_"+items[i].id+"' style='width:100% !important'><option value='0'>Đang theo dõi</option><option value='1'>Ngừng theo dõi</option></select>")
					$("#tinhtrang_linhkien tbody").append(tr);
					buildGrid("#tinhtrang_linhkien");
				}
				$(".tinhtranglinhkien").show();
				$(".thaythelinhkien").show();
				hideLoader($('#tab_create_repair'));
			})
		}else
		{
			$("#makhachhang").val("");
			$("#tenkhachhang").val("");
			$("#mamay").val("");
			$("#tenmay").val("");
			$("#socounterdadung").val("");
			$(".tinhtranglinhkien").hide();
			$(".thaythelinhkien").hide();
			serial_value = 0;
		}
	})
	
	$("#serial").trigger("change");
	
	$(".linhkien_select").chosentable({
		max_selected_options:1,
		search_contains: true,
		no_results_text: 'Không tìm thấy:',
		template: function (text, templateData) {
	    	return [
	      		"<div class='k-grid-content'><table><tbody><tr><td>" + templateData.ma + "</td>",
	      		"<td>" + templateData.ten + "</td></tr></tbody></table>",      
	    	].join("");
	  	},
	  	headerTemplate:'<div class="k-grid-header"><div class="k-grid-header-wrap"> <table style="width:100%"><thead><tr><th class="k-header" style="width:50%">Mã linh kiện</th><th class="k-header" >Tên linh kiện</th></tr></thead></table></div></div>'
	});
}

function buildGrid(el)
{
	$(el).find("tbody tr").each(function(index){
		if(index % 2 != 0) $(this).addClass("k-alt");
	})
}

function getPercentClass(percent)
{
	var percent_class = "";
	
	if(percent <= 50)
	{
		percent_class = "";
	}else if(percent > 50 && percent <= 80)
	{
		percent_class = "progress-warning";
	}else if(percent > 80)
	{
		percent_class = "progress-danger";
	}
	return percent_class;
}

function calculateClosing(closing,lastuse,currentuse,tuoitho)
{
	var counter_diff = parseInt(currentuse) - parseInt(lastuse);
	var closing_diff = parseInt(closing) - parseInt(counter_diff);
	var diff = closing_diff * 100 / parseInt(tuoitho);
	diff = (diff > 100)?100:diff;
	return diff;
}

function calculateTinhtrang(closing,tuoitho)
{
	var diff = closing * 100 / parseInt(tuoitho);
	diff = (diff > 100)?100:diff;
	return diff;
}

function initCreaterepair()
{
	
	$("#form_create_repair").validate({  
		errorPlacement: function(error, element) {
			if($(element).hasClass("error"))
			{
				hideLoader($('#form_create_repair'));
			}
            error.remove();          
        },
        onkeyup:false,
        onfocusout:false,
        rules:{
            inventory_id:{
                required:true
            },    
            socounter:{
            	required:true,
            	checkCounter:true
            }
            
        },
        messages:{
        	inventory_id:{
                required:'Vui lòng chọn serial'
            },    
            socounter:{
            	required:"Vui lòng nhập số counter",
            	checkCounter:"Vui lòng nhập số counter lớn hơn số counter đã dùng"
            }
        }
    })
    
    jQuery.validator.addMethod('checkCounter', function(value,element) {
        var counter = $.trim($("#socounterdadung").val());
        var check = true;
        if(counter == "")
        {
        	counter = 0;
        }	
        if(parseInt(counter) > parseInt(value) )
        {
        	check = false;
        }	
        return check;
    })
    
    $('#form_create_repair').ajaxForm({
    	beforeSubmit:function(){   		
    		showLoader($('#form_create_repair'));
    	},
    	success:function(response){
    		var obj = checkJSON(response);
    		if(obj.is_json)
    		{
    			if(!obj.result.success)
        		{
        			var error = obj.result.error;
        			alertify.alert(error);
        		}
    		}
    		else
    		{  			
    			window.location.hash = "repair";
    		}
    		hideLoader($('#form_create_repair'));
    	}
    });
}




